import React, {useEffect, useState} from "react";
import {ColumnsType} from "antd/es/table";
import {Button, message, Popconfirm, Space, Table} from "antd";
import {DeleteOutlined, DownloadOutlined, EditOutlined} from "@ant-design/icons";
import {httpDelete, httpGet, Result} from "@/utils/http";
import {ServerAdd, ServerUpdate} from "@/pages/script/components";
import {DataNode} from "@/pages/script";
import {ServerUpdateProp} from "@/pages/script/components/server-update";
import {ServerGroupProp} from "@/pages/script/components/group";

interface ItemProp {
    sId: number;
    updateNode: (data: DataNode) => void;
    deleteNode: (id: React.Key | React.Key[]) => void;
    insertNode: (data: DataNode) => void;
}

interface ServerItemProp {
    id: number;
    key: string;
    group_id: number;
    group_name: string;
    item_type: number;
    curr_path: string;
    title: string;
    desc: string;
    work_home: string;
    work_path: string;
    create_id: string;
    create_time: string;
}

export const ServerItem: React.FC<ItemProp> = ({sId,updateNode, deleteNode, insertNode}) => {
    const columns: ColumnsType<ServerItemProp> = [
        {
            title: '序号',
            key: 'index',
            dataIndex: 'index',
            align: 'center',
            width: 100,
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '服务名称',
            key: 'title',
            dataIndex: 'title',
            align: 'center',
        },
        {
            title: '服务路径',
            key: 'work_path',
            dataIndex: 'work_path',
            align: 'center',
        },
        {
            title: '描述',
            key: 'desc',
            dataIndex: 'desc',
            align: 'center',
        },
        {
            title: '创建时间',
            key: 'create_time',
            dataIndex: 'create_time',
            align: 'center',
        },
        {
            title: '操作',
            key: 'active',
            align: 'center',
            width: 150,
            render: (text, record, index) => (
                <Space size={'small'}>
                    <Button size="small" type="link" icon={<DownloadOutlined />} />
                    <Button size="small" type="link" icon={<EditOutlined />} onClick={() => openUpdateModel(record)} />
                    <Popconfirm
                        placement="bottom"
                        title="警告"
                        description="删除当前分组后，下属的所有服务都将无法使用，确认删除吗？"
                        onConfirm={() => deleteServer(record.id, record.key)}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button size="small" type="link" danger icon={<DeleteOutlined />}/>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    const [loading, setLoading] = useState<boolean>(false);
    const [datasource, setDatasource] = useState<ServerItemProp[]>([]);
    const [addVisible, setAddVisible] = useState<boolean>(false);
    const [updateVisible, setUpdateVisible] = useState<boolean>(false);
    const [currData, setCurrData] = useState<ServerUpdateProp | undefined>(undefined)

    const loadData = () => {
        setLoading(true);
        httpGet<Result<ServerItemProp[] | string>, any>('/server/item/list', {gId: sId}).then(res => {
            if (res.code === 100200) {
                setDatasource(res.result as ServerItemProp[]);
            } else {
                message.error(res.result as string)
            }
        }).catch(err => {
            console.error(err)
        }).finally(() => {setLoading(false)})
    }

    const deleteServer = (id: number | number[], key: string | string[]) => {
        console.log("id => ", id, "key => ", key);
        // return;
        setLoading(true);
        httpDelete<Result<string>, any>('/server/group/delete', {ids: id}).then(res => {
            if (res.code === 100200) {
                message.success(res.message);
                const temp = datasource.filter(item => {
                    if ((Array.isArray(id))) {
                        return !(id as number[]).includes(item.id)
                    } else {
                        return id !== item.id
                    }
                })
                setDatasource([...temp])
                deleteNode(key);
            } else {
                message.error(res.message);
            }
        }).catch(err => {console.error(err)}).finally(() => setLoading(false));

    }

    const closeModel = (types: "update" | "insert", data?: DataNode) => {
        if (types === "insert") {
            setAddVisible(false);
            if (data !== undefined) {
                loadData();
                insertNode({...data, children: undefined, isLeaf: true});
            }
        }
        if (types === "update") {
            setUpdateVisible(false);
            if (data !== undefined) {
                loadData();
                updateNode({...data, children: undefined, isLeaf: true});
            }
        }

    }

    const openUpdateModel = (data: ServerItemProp) => {
        setUpdateVisible(true);
        setCurrData({id: data.id, parent_id: data.group_id, title: data.title, desc: data.desc, work_path: data.work_path})
    }

    useEffect(() => { loadData() }, [sId])

    return <div>
        <Space>
            <Button size='small' type='primary' onClick={() => setAddVisible(true)}>创建服务</Button>
            <Button size='small' type='primary' danger>删除服务</Button>
        </Space>
        <Table
            size={'small'}
            style={{ marginTop: 10 }}
            columns={columns}
            dataSource={datasource}
            bordered
            pagination={false}
            loading={loading}
        />
        <ServerAdd groupId={sId} visible={addVisible} onCancel={(data) => closeModel('insert', data)} />
        <ServerUpdate initData={currData!} visible={updateVisible} onCancel={(data) => closeModel('update', data)} />
    </div>
}
